﻿using System.Linq;
using System.Web.Mvc;
using System.Collections.Generic;

using ASPNETMVCApplication.Code.Filters;
using ASPNETMVCApplication.Repositories;
using ASPNETMVCApplication.ActionServiceReference;
using ASPNETMVCApplication.Code.HtmlHelpers;
using ASPNETMVCApplication.Controllers;
using ASPNETWebApplication;
using ASPNETMVCApplication.Areas.Supp.Models;
using ASPNETMVCApplication.Areas.Shop.Models;
using ASPNETMVCApplication.Areas.Supp.ViewModels;
using System;

namespace ASPNETMVCApplication.Areas.Supp.Controllers
{
    public class ProductController : Controller
    {
        private ICategoryRepository _categoryRepository;
        private IProductRepository _productRepository;
        private ITrafficRepository _trafficRepository;
        private ISupplierRepository _supplierRepository;

        public ProductController()
            : this(new CategoryRepository(), new ProductRepository(),new TrafficRepository(),new SupplierRepository())
        {
        }

        /// <summary>
        /// Overloaded 'injectable' Constructor for ShopController.
        ///
        /// Pattern: Constructor Dependency Injection (DI).
        /// </summary>
        /// <param name="categoryRepository"></param>
        /// <param name="productRepository"></param>
        /// <param name="cartRepository"></param>
        public ProductController(ICategoryRepository categoryRepository, IProductRepository productRepository,ITrafficRepository trafficRepository,ISupplierRepository supplierRespository)
        {
            _trafficRepository = trafficRepository;
            _categoryRepository = categoryRepository;
            _productRepository = productRepository;
            _supplierRepository = supplierRespository;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult SearchCategory()
        {
            try {
                List<Supplier> listSupplier = _supplierRepository.GetList(null).ToList();
                List<SelectListItem> listItem = new List<SelectListItem>();
                foreach (Supplier supp in listSupplier)
                {
                    listItem.Add(new SelectListItem { Text = supp.CompanyName, Selected = false, Value = supp.SupplierId.ToString() });
                }
                ViewData["ListSupp"] = listItem;
                return View();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            
        }

        [HttpPost]
        public ActionResult SearchCategory(SearchCategoryModel category)
        {
            //Cập nhật lại DateFrom, DateTo nếu rỗng
            var categoryList = _categoryRepository.Search(category.DateFrom, category.DateTo, category.FirstPoint, category.LastPoint, category.SupplierId, category.TrafficId, "CategoryId", "ASC");

            List<ProductViewModels> listProcViewModel=new List<ProductViewModels>();
            ProductViewModels procViewModel=null;
            List<Supplier> SuppList=null; 
            List<Category> CateList=null;
            List<Product> ProcList=null; 
            Supplier supplier=null;

            if (categoryList.Count > 0)
            {
                SuppList = new List<Supplier>();
                var IdList = new List<int>();
                for (int i = 0; i < categoryList.Count; i++)
                {
                   // supplier = new Supplier();
                    supplier = _supplierRepository.Get(categoryList[i].SupplierId);
                    if(SuppList.Count == 0)
                    {
                        SuppList.Add(supplier);
                        IdList.Add(categoryList[i].SupplierId);
                    }
                    else if (IdList.Contains(categoryList[i].SupplierId) == false)
                    {                       
                        SuppList.Add(supplier);
                        IdList.Add(categoryList[i].SupplierId);
                    }
                }

                       CateList = new List<Category>();
                for (int j = 0; j < SuppList.Count; j++)
                {
                //Lấy danh sách category                
                    for (int k = 0; k < categoryList.Count; k++)
                    {
                        if (categoryList[k].SupplierId == SuppList[j].SupplierId)
                        {
                            CateList.Add(categoryList[k]);
                        }
                    }                
                 }
                //Hiển thị nội dung
                ProcList = new List<Product>();
                procViewModel = new ProductViewModels();
                 for (int h = 0; h < CateList.Count; h++)
                 {
                    var productList = _productRepository.Search(CateList[h].CategoryId, "ChairNumber", "ASC");
                    ProcList = productList.ToList<Product>();
                    procViewModel.ListCate = CateList;
                    procViewModel.Supp = supplier;
                    procViewModel.ListProc = ProcList;
                    listProcViewModel.Add(procViewModel);   
                 }                             
        }
           
            //Creat object ProductViewModelsc
            //ProductViewModels procViewModel = new ProductViewModels { ListCate = CateList, ListProc = ProcList, ListSupp = SuppList };
            ViewData["ListTick"] = listProcViewModel;
            List<Supplier> listSupplier = _supplierRepository.GetList(null).ToList();
            List<SelectListItem> listItem = new List<SelectListItem>();
            foreach (Supplier supp in listSupplier)
            {
                listItem.Add(new SelectListItem { Text = supp.CompanyName, Selected = false, Value = supp.SupplierId.ToString() });
            }
            ViewData["ListSupp"] = listItem;
            return View();
        }


        [HttpPost]
        public ActionResult TicketBuy(FormCollection form)
        {
            int cateId= Int32.Parse(Request.Form["CateID"].ToString());
            int suppId=Int32.Parse(Request.Form["SuppID"].ToString());
            Supplier supp = _supplierRepository.Get(suppId);
            Category categories = _categoryRepository.Get(cateId);
            int trafficId = categories.TrafficId;
            Traffic traffic = _trafficRepository.Get(trafficId, suppId);

            List<Product> ghe = _productRepository.Search(categories.CategoryId, "ChairNumber", "ASC").ToList<Product>();
            List<Product> ghemua = new List<Product>();
            for (int i = 0; i < ghe.Count; i++)
            {
                var check = Request.Form.Get("check" + ghe[i].ChairNumber.ToString());
                if (check =="on")
                {
                    ghemua.Add(ghe[i]);
                }
            }
                
            //Gan gia tri cho session
            CartViewModels cartView = new CartViewModels { _supplier = supp, _traffic = traffic,_categories=categories, _ghemua = ghemua };
            List<CartViewModels> listCart = new List<CartViewModels>();

            if (Session["CartView"] == null)
            {
                listCart.Add(cartView);
                Session.Add("CartView", listCart);
            }
            else
            {
                listCart = (List<CartViewModels>)Session["CartView"];
                listCart.Add(cartView);
                Session["CartView"] = listCart;
            }
            
            return View();
        }

        [HttpGet]
        public ActionResult UpdatePrice()
        {
            if (Session["SuppId"] != null)
            {
                List<Traffic> listTraffic=_trafficRepository.GetList(null).ToList();
                List<SelectListItem> listItem = new List<SelectListItem>();
                foreach (Traffic traffic in listTraffic)
                {
                    listItem.Add(new SelectListItem { Text = traffic.TrafficName, Selected = false, Value = traffic.TrafficId.ToString() });
                }
                ViewData["ListTraffic"] = listItem;

                return View();
            }
            else
            {
                return RedirectToAction("Login", "Supplier", new { area = "Supp" });
            }
            
        }

        [HttpPost]
        public String UpdatePrice(SearchCategoryModel category)
        {
            var categoryList = _categoryRepository.Search(category.DateFrom, category.DateTo, category.FirstPoint, category.LastPoint, category.SupplierId, category.TrafficId, "CategoryId", "ASC");

            List<Product> ProcList = null;

            if (categoryList.Count > 0)
            {
                ProcList = new List<Product>();
                for (int h = 0; h < categoryList.Count; h++)
                {
                    var productList = _productRepository.Search(categoryList[h].CategoryId, "ChairNumber", "ASC");
                    if (productList.Count > 0)
                    {
                        for (int i = 0; i < productList.Count; i++)
                        {
                            Product product = new Product();
                            product = productList[i];
                            product.UnitPrice = category.NewPrice;
                            _productRepository.Update(product);
                        }
                    }
                }
                return "Cập nhật giá vé thành công ";
            }
            else
            {
                return "Không có chuyến xe nào trong khoản ngày từ " + category.DateFrom + " đến ngày " + category.DateTo;
            }
            
        }
    }
}
